package com.wangyadong.hobby.metric.gauge.lession1;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/12/1814:55
 * 18-12-18 15:19:12 ==============================================================
 * <p>
 * -- Meters ----------------------------------------------------------------------
 * tqs
 * count = 7
 * mean rate = 6.96 events/minute
 * 1-minute rate = 8.91 events/minute
 * 5-minute rate = 11.10 events/minute
 * 15-minute rate = 11.68 events/minute
 * volume
 * count = 2614
 * mean rate = 2599.20 events/minute
 * 1-minute rate = 5529.53 events/minute
 * 5-minute rate = 8849.27 events/minute
 * 15-minute rate = 9733.73 events/minute
 **/
public class MeterExample {
    /**
     * 三部曲
     * private final static MetricRegistry registry = new MetricRegistry();
     * 第二部，选择meter
     * private final static Meter requestMeter = registry.meter("tqs");
     * 第三部
     * mark(ewma)
     */
    private final static MetricRegistry registry = new MetricRegistry();

    //注册到metric
    private final static Meter requestMeter = registry.meter("tqs");
    private final static Meter sizeMeter = registry.meter("volume");


    public static void main(String[] args) {
        ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
                .convertRatesTo(TimeUnit.MINUTES)
                .convertDurationsTo(TimeUnit.MINUTES)
                .build();

        reporter.start(10, TimeUnit.SECONDS);
        for (; ; ) {
            handleRequest(new byte[ThreadLocalRandom.current().nextInt(1000)]);
            randomSleep();
        }
    }

    private static void handleRequest(byte[] request) {
        requestMeter.mark();
        sizeMeter.mark(request.length);
        randomSleep();
    }

    //doing something
    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
